<template>
  <div class="min-h-screen flex items-center justify-center bg-gray-50 py-12 px-4 sm:px-6 lg:px-8">
    <div class="max-w-md w-full space-y-8 bg-white p-8 rounded-lg shadow-md transition-all duration-300 hover:shadow-lg">
      <!-- Logo区域 -->
      <div class="flex flex-col items-center justify-center">
        <img src="@/assets/logo.svg" alt="CMS Logo">
        <h1 class="text-2xl font-bold text-gray-900 text-center">加入我们</h1>
      </div>

      <!-- 注册表单 -->
      <el-form
        ref="registerForm"
        :model="formData"
        :rules="rules"
        class="mt-8 space-y-6"
        @submit.prevent="handleSubmit"
        validate-on-rule-change
      >
       

        <!-- 用户名 -->
        <el-form-item prop="username">
          <el-input
            v-model="formData.username"
            placeholder="请输入用户名"
            type="text"
            prefix-icon="User"
            autocomplete="username"
            maxlength="20"
            @blur="() => formData.username = formData.username.trim()"
          />
        </el-form-item>

        <!-- 密码（核心优化区域） -->
        <el-form-item 
          prop="password"
          :error="passwordErrorMsg"
          class="!mb-0"
        >
          <el-input
            v-model="formData.password"
            placeholder="请输入密码"
            type="password"
            prefix-icon="Lock"
            show-password
            @input="handlePasswordInput"
            autocomplete="new-password"
            maxlength="20"
          >
            <!-- 密码达标后显示对勾图标 -->
            <template #suffix v-if="isPasswordValid && formData.password">
              <el-icon class="text-green-500">
                <Check />
              </el-icon>
            </template>
          </el-input>

          <!-- 密码强度指示器 -->
          <div v-if="formData.password.length > 0" class="mt-2 space-y-1">
            <!-- 强度文本：达标后显示"符合要求" -->
            <div class="text-sm" :class="isPasswordValid ? 'text-green-600' : 'text-gray-600'">
              {{ isPasswordValid ? '密码符合要求' : `密码强度：${strengthText}` }}
            </div>
            
            <!-- 强度条 -->
            <div class="h-1.5 bg-gray-200 rounded-full overflow-hidden">
              <div
                class="h-full transition-all duration-300 ease-in-out"
                :style="{ width: isPasswordValid ? '100%' : `${(passwordStrength / 5) * 100}%` }"
                :class="isPasswordValid ? 'bg-green-500' : strengthBgClass"
              ></div>
            </div>
            
            <!-- 规则提示：仅未达标时显示 -->
            <div v-if="!isPasswordValid" class="text-xs text-gray-500">
              密码必须包含数字和字母，长度6-20位
            </div>
          </div>
        </el-form-item>

        <!-- 确认密码 -->
        <el-form-item 
          prop="confirmPassword"
          :error="confirmPasswordErrorMsg"
        >
          <el-input
            v-model="formData.confirmPassword"
            placeholder="请确认密码"
            type="password"
            prefix-icon="Lock"
            show-password
            autocomplete="new-password"
            maxlength="20"
            @input="checkConfirmPassword"
          >
            <!-- 确认密码达标后显示对勾 -->
            <template #suffix v-if="isConfirmPasswordValid && formData.confirmPassword">
              <el-icon class="text-green-500">
                <Check />
              </el-icon>
            </template>
          </el-input>
        </el-form-item>

         <!-- 邮箱 + 发送验证码 -->
         <el-form-item prop="email">
          <div class="flex items-center w-full space-x-2">
            <el-input class="flex-1"
              v-model="formData.email"
              placeholder="请输入邮箱"
              type="email"
              prefix-icon="Message"
              :disabled="countdown > 0"
              autocomplete="email"
              @blur="() => formData.email = formData.email.trim()"
            />
            <el-button
              type="primary"
              :disabled="countdown > 0 || !formData.email"
              @click="sendVerificationCode"
              class="whitespace-nowrap"
            >
              {{ countdown ? `${countdown}s后重发` : '发送验证码' }}
            </el-button>
          </div>
        </el-form-item>

        <!-- 验证码输入 -->
        <el-form-item prop="code">
          <el-input
            v-model="formData.code"
            placeholder="请输入验证码"
            type="text"
            prefix-icon="Tickets"
            autocomplete="one-time-code"
            maxlength="4"
            @input="formData.code = formData.code.replace(/[^0-9]/g, '')"
          />
        </el-form-item>

        <!-- 服务协议 -->
        <el-form-item prop="agreement" class="!mb-0">
          <el-checkbox v-model="formData.agreement" class="text-sm">
            我已阅读并同意
            <el-link type="primary" @click="showAgreement" class="!text-primary cursor-pointer">《服务协议》</el-link>
            和
            <el-link type="primary" @click="showPrivacy" class="!text-primary cursor-pointer">《隐私政策》</el-link>
          </el-checkbox>
        </el-form-item>

        <!-- 提交按钮 -->
        <el-form-item>
          <el-button
            type="primary"
            native-type="submit"
            class="w-full"
            :loading="loading"
            :disabled="!formValid"
          >
            注册
          </el-button>
        </el-form-item>

        <!-- 登录链接 -->
        <div class="text-center mt-4 text-sm text-gray-600">
          已有账号？
          <router-link to="/login" class="text-primary hover:text-primary/80 transition-colors text-blue-700">去登录</router-link>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { Check } from '@element-plus/icons-vue'

// 导入工具函数和API
import { genCode } from './util/index.js'
import { sendEmail, toReg ,} from './api/index.js'

// 路由实例
const router = useRouter()

// 表单核心状态
const registerForm = ref(null)
const loading = ref(false)
const countdown = ref(0)
const passwordStrength = ref(0)
let countdownTimer = null

// 密码验证状态管理
const passwordErrorMsg = ref('')
const confirmPasswordErrorMsg = ref('')
const isPasswordValid = ref(false)
const isConfirmPasswordValid = ref(false)

// 表单数据
const formData = reactive({
  email: '',
  username: '',
  password: '',
  confirmPassword: '',
  code: '',
  agreement: false
})

// 密码强度配置
const PASSWORD_STRENGTH = {
  TEXT: ['未输入', '非常弱', '弱', '中等', '强', '非常强'],
  BG_CLASS: [
    'bg-transparent',
    'bg-red-500',
    'bg-orange-500',
    'bg-yellow-500',
    'bg-blue-500',
    'bg-green-500'
  ]
}

// 密码输入处理
const handlePasswordInput = () => {
  // 计算密码强度
  passwordStrength.value = getPasswordStrength(formData.password)
  
  // 验证密码规则
  const isLengthValid = formData.password.length >= 6 && formData.password.length <= 20
  const hasLetterAndNumber = /(?=.*[a-zA-Z])(?=.*\d)/.test(formData.password)
  isPasswordValid.value = isLengthValid && hasLetterAndNumber

  // 动态错误提示
  if (!formData.password) {
    passwordErrorMsg.value = '请输入密码'
  } else if (!isLengthValid) {
    passwordErrorMsg.value = '密码长度需在6-20个字符之间'
  } else if (!hasLetterAndNumber) {
    passwordErrorMsg.value = '密码必须包含字母和数字'
  } else {
    passwordErrorMsg.value = '' // 符合要求时清空提示
  }

  // 同步验证确认密码
  checkConfirmPassword()
}

// 确认密码验证
const checkConfirmPassword = () => {
  if (!formData.confirmPassword) {
    confirmPasswordErrorMsg.value = '请确认密码'
    isConfirmPasswordValid.value = false
  } else if (!isPasswordValid.value) {
    confirmPasswordErrorMsg.value = ''
    isConfirmPasswordValid.value = false
  } else {
    const isMatch = formData.confirmPassword === formData.password
    confirmPasswordErrorMsg.value = isMatch ? '' : '两次输入的密码不一致'
    isConfirmPasswordValid.value = isMatch
  }
}

// 密码强度计算
const getPasswordStrength = (password) => {
  if (!password) return 0
  let strength = 0
  
  // 长度评分
  if (password.length >= 6) strength += 1
  if (password.length >= 12) strength += 1
  
  // 字符类型评分
  if (/[a-z]/.test(password)) strength += 1
  if (/[A-Z]/.test(password)) strength += 1
  if (/[0-9]/.test(password)) strength += 1
  
  // 特殊字符加分
  if (/[^a-zA-Z0-9]/.test(password)) strength = Math.min(strength + 1, 5)
  
  return Math.min(strength, 5)
}

// 计算属性
const strengthText = computed(() => PASSWORD_STRENGTH.TEXT[passwordStrength.value])
const strengthBgClass = computed(() => PASSWORD_STRENGTH.BG_CLASS[passwordStrength.value])

// 表单验证规则
const rules = computed(() => ({
  email: [
    { required: true, message: '请输入邮箱地址', trigger: ['blur', 'change'] },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: ['blur', 'change'] }
  ],
  username: [
    { required: true, message: '请输入用户名', trigger: ['blur', 'change'] },
    { min: 3, max: 20, message: '用户名长度需在3-20个字符之间', trigger: ['blur', 'change'] },
    {
      validator: (_, value, callback) => {
        const reg = /^[a-zA-Z0-9_]{3,20}$/
        reg.test(value) ? callback() : callback(new Error('用户名仅允许字母、数字和下划线'))
      },
      trigger: ['blur', 'change']
    }
  ],
  password: [
    { required: true, message: () => passwordErrorMsg.value, trigger: ['blur', 'change'] }
  ],
  confirmPassword: [
    { required: true, message: () => confirmPasswordErrorMsg.value, trigger: ['blur', 'change'] }
  ],
  code: [
    { required: true, message: '请输入验证码', trigger: ['blur', 'change'] },
    { min: 4, max: 6, message: '验证码长度需在4-6位之间', trigger: ['blur', 'change'] },
    { pattern: /^\d+$/, message: '验证码仅允许数字', trigger: ['blur', 'change'] }
  ],
  agreement: [
    {
      validator: (_, value, callback) => {
        value ? callback() : callback(new Error('请阅读并同意服务条款和隐私政策'))
      },
      trigger: 'change'
    }
  ]
}))

// 表单整体有效性
const formValid = computed(() => {
  return formData.email && 
         formData.username && 
         formData.password && 
         formData.confirmPassword && 
         formData.code && 
         formData.agreement && 
         isPasswordValid.value && 
         isConfirmPasswordValid.value
})

// 发送验证码
const sendVerificationCode = async () => {
  if (countdown.value > 0) return
  if (!formData.email) {
    ElMessage.warning('请先输入邮箱地址')
    return
  }

  // 邮箱格式预验证
  const emailReg = /^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$/
  if (!emailReg.test(formData.email)) {
    ElMessage.warning('请输入有效的邮箱地址')
    return
  }

  // 启动倒计时
  countdown.value = 60
  if (countdownTimer) clearInterval(countdownTimer)
  countdownTimer = setInterval(() => {
    countdown.value--
    if (countdown.value <= 0) {
      clearInterval(countdownTimer)
      countdownTimer = null
    }
  }, 1000)

  // 发送验证码请求
  try {
    const params = { 
      email: formData.email.trim(), 
      code: genCode(),
      type: 'register'
    }
    const res = await sendEmail(params)
    if (res?.code === 200) {
      ElMessage.success('验证码已发送至您的邮箱，请查收')
    } else {
      ElMessage.error(res?.message || '验证码发送失败，请重试')
      clearInterval(countdownTimer)
      countdown.value = 0
      countdownTimer = null
    }
  } catch (error) {
    console.error('验证码发送异常:', error)
    ElMessage.error('网络异常，验证码发送失败')
    clearInterval(countdownTimer)
    countdown.value = 0
    countdownTimer = null
  }
}

// 服务协议弹窗
const showAgreement = () => {
  ElMessageBox.alert(
    `<h3 class="font-medium mb-2">服务协议</h3>
    <p class="text-sm mb-1">1. 您需保证注册信息真实有效，如有变更请及时更新</p>
    <p class="text-sm mb-1">2. 不得使用本平台从事违法违规活动</p>
    <p class="text-sm">3. 平台有权在法律法规范围内调整服务条款</p>`,
    '服务协议',
    { 
      confirmButtonText: '我已阅读并同意', 
      type: 'info', 
      dangerouslyUseHTMLString: true, 
      center: true, 
      width: '380px' 
    }
  ).then(() => {
    formData.agreement = true
  })
}

// 隐私政策弹窗
const showPrivacy = () => {
  ElMessageBox.alert(
    `<h3 class="font-medium mb-2">隐私政策</h3>
    <p class="text-sm mb-1">1. 仅收集邮箱用于账号验证，不泄露给第三方</p>
    <p class="text-sm mb-1">2. 密码通过加密处理存储，保障账号安全</p>
    <p class="text-sm">3. 您可随时查阅、修改个人信息</p>`,
    '隐私政策',
    { 
      confirmButtonText: '我已阅读并同意', 
      type: 'info', 
      dangerouslyUseHTMLString: true, 
      center: true, 
      width: '380px' 
    }
  ).then(() => {
    formData.agreement = true
  })
}

// 注册处理
const handleRegister = async () => {
  try {
    const params = {
      email: formData.email.trim(),
      username: formData.username.trim(),
      password: formData.password,
      code: formData.code.trim()
    }
    const res = await toReg(params)
    if (res?.code === 200) {
      ElMessage.success('注册成功！即将跳转到登录页')
      setTimeout(() => {
        router.push('/login')
      }, 1500)
    } else {
      ElMessage.error(res?.message || '注册失败，请检查信息后重试')
    }
  } catch (error) {
    console.error('注册接口异常:', error)
    ElMessage.error('网络异常，注册失败，请稍后重试')
  }
}

// 表单提交
const handleSubmit = async () => {
  if (!formValid.value || loading.value) return

  try {
    await registerForm.value.validate()
    loading.value = true
    await handleRegister()
  } catch (error) {
    if (error.name === 'ValidationError') {
      ElMessage.warning('请完善并修正表单信息后提交')
    } else {
      ElMessage.error(error.message || '注册失败，请稍后重试')
    }
    console.error('表单提交异常:', error)
  } finally {
    loading.value = false
  }
}

// 组件卸载清理
onUnmounted(() => {
  if (countdownTimer) {
    clearInterval(countdownTimer)
    countdownTimer = null
  }
})
</script>
